package delayMessage.queue;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟任务的任务体
 *
 * Created by Zhou_Bing on 2018/9/29.
 */
public class Job implements Delayed{

    private int id;
    private Class clz;
    private Method method;
    private Object[] args;
    private JobCallBack callBack;

    private Long executeTime;//任务执行时间

    Job(int id, Class clz, Method method, Object[] args,long delayTime){
        this.id = id;
        this.clz = clz;
        this.method = method;
        this.args = args;
        this.executeTime = TimeUnit.NANOSECONDS.convert(delayTime,TimeUnit.MILLISECONDS)+System.nanoTime();

    }

    Job(int id,JobCallBack callBack,long delayTime){
        this.id = id;
        this.callBack = callBack;
        this.executeTime = TimeUnit.NANOSECONDS.convert(delayTime,TimeUnit.MILLISECONDS)+System.nanoTime();
    }


    public int getId(){
        return this.id;
    }

    /**
     *  延迟任务是否到时 是按照这个方法进行判断的
     *
     *  返回负数表明还没到期
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.executeTime-System.nanoTime(),TimeUnit.NANOSECONDS);
    }


    /**
     * 用于延迟队列的排序
     *
     * 在上面的，先执行
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        Job job = (Job) o;
        return Integer.compare(this.id,job.id);
    }

    public void execute(){
        try {
            this.method.invoke(clz.newInstance(),args);
        } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
        }
    }

    public void callBack(){
        this.callBack.execute();
    }
}
